package com.weishao.learn;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.pentaho.di.core.KettleEnvironment;
import org.pentaho.di.core.exception.KettleException;
import org.pentaho.di.core.logging.KettleLogStore;
import org.pentaho.di.core.variables.Variables;
import org.pentaho.di.core.xml.XMLHandler;
import org.pentaho.di.trans.Trans;
import org.pentaho.di.trans.TransMeta;

/**
 * 基于Kettle API从 .ktr 文件生成transMeta对象
 * 
 * 说明：在DI设计器中设计好转换之后，该转换会以 .ktr 文件的形式持久存储到本地磁盘。并且Kettle提供了方法调用使得
 * 能从 .ktr 文件解析出 transMeta对象。而transMeta对象就是表征转换运行的一个JAVA对象。
 * 
 * 参考地址：
 *  https://blog.csdn.net/weixin_33962621/article/details/90121918
 *  
 * @author tang
 *
 */
public class LoadConfigApplication {

	public static void main(String[] args) throws KettleException {
		KettleEnvironment.init();
		String filename="d:\\study.ktr";
		Document document = XMLHandler.loadXMLFile(filename);
        Node root = (Node) document.getDocumentElement();

		TransMeta transMeta=new TransMeta();
		 transMeta = new TransMeta();
         transMeta.loadXML(root, filename, null, null, true, new Variables(), null);
		
		String transXml = transMeta.getXML();
		System.out.println("=================");
		System.out.println(transXml);

		Trans trans = new Trans(transMeta);
		try {
			trans.execute(null);
			System.out.println("start............");
			trans.waitUntilFinished();
			System.out.println("end............");
			if (trans.getErrors() > 0) {
				String errMsg = KettleLogStore.getAppender().getBuffer(trans.getLogChannelId(), false).toString();
				throw new KettleException(errMsg);
			}
		} finally {
			trans.cleanup();
		}

	}

}
